/**
 * Created by Administrator on 18-12-28.
 */
let router = require('../router/Router');
let P = require("bluebird");
let userDao = require('../dao/userDao');
let Token = require('../token');
let phttp = require('../util/phttp');
let cnst = require('../const');
let fileUtil = require('../util/fileUtil');
let timeUtil = require('../util/timeUtil');
let ipUtil = require('../util/ipUtil');
let bcryptUtil = require('../util/bcryptUtil');

let redis = require('../dao/redis');
let redisConst = require('../const/redisConst');
let cmService = require('../service/cmService');
let userService = require('../service/userService');

router.dkRegister = P.coroutine(function* (req, res) {
    let phone = req.query.phone;
    let phoneCode = req.query.phoneCode;
    let nickname = req.query.nickname;
    let password = req.query.password;
    let sex = req.query.sex;
    let inviteCode = req.query.invitecode;
    // if (!(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
    //     console.logw("手机号码格式不对 ", phone);
    //     res.send({ code: 500, msg: '手机号码格式不对' });
    //     return;
    // }

    let code = Number(phoneCode);
    if (isNaN(code) || code > 99999) {
        res.send({ code: 500, msg: '无效验证码' });
        return;
    }

    const cacheKey = redisConst.PWD_VALID_CODE + ":" + phone;
    let cacheCode = yield redis.getString(cacheKey);
    if (code + "" !== cacheCode) {
        console.logw("正确的手机验证码是", cacheCode, phone);
        res.send({ code: 500, msg: '请输入正确的手机验证码' });
        return;
    }

    if (!nickname || nickname.length > 20) {
        res.send({ code: 500, msg: '昵称不能为空或者长度不能大于20' });
        return;
    }

    if (password && password.length < 8) {
        res.send({ code: 500, msg: '请输入8位以上的密码' });
        return;
    }

    // let psw = Token.aesEncodeDef(password);
    let psw = bcryptUtil.hash(password);
    let ip = ipUtil.getIp(req, res);
    let headimgurl = Math.floor(Math.random() * 100) % 83 + 1;


    let ret = yield userService.createUserWithPhone(phone, nickname, headimgurl, ip, psw, code, sex);
    if (ret == null) {
        console.logw("createUser failed ", phone, nickname, headimgurl, ip, psw, code);
        res.send({ code: 500, msg: 'create user failed' });
        return;
    }

    if (ret.code === 500) {
        console.logw("注册失败:" + ret.msg);
        res.send(ret);
        return;
    }

    if (inviteCode && inviteCode !== "") {
        let inviteCodeDecode = Token.aesDecodeDef(inviteCode);
        if (inviteCodeDecode && inviteCodeDecode !== ''){
            inviteCode = inviteCodeDecode;
        }

        for (let i = 0; i < 3; i++) {
            try {
                let result = yield cmService.addChild({ acctId: ret.uid, pAcctId: inviteCode });
                if (result) {
                    break;
                }
            } catch (e) {
                console.logw("cm service add child failed:", e);
                yield timeUtil.timeout(1000);
            }
        }
    }

    ret.token = Token.aesEncodeDef(ret.uid);
    ret.stoken = Token.aesEncodeDef(ip);
    ret.code = 200;
    res.send(ret);
});

router.get('/weixin/dkReg', function (req, res) {
    router.dkRegister(req, res).catch(function (e) {
        console.logg("dkRegister exception ", e.message);
        if (!res.finished) {
            res.send({ code: 500, msg: "exception" });
        }
    });
});


router.dk_getPhoneVerifycode = P.coroutine(function* (req, res) {
    let phone = req.query.phone;
    // if (!(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
    //     console.logg("手机号码格式不对 ", phone);
    //     res.send({ code: 500, msg: '请输入正确的手机号码' });
    //     return;
    // }

    let ip = ipUtil.getIp(req, res);
    let key = ip + "_" + phone;
    let getPhoneTick = yield router.redis.getString(key);
    let time = (new Date().getTime() - Number(getPhoneTick)) / 1000;
    if (time < 50) {
        console.logg("获取手机验证码太频繁了");
        res.send({ code: 500, msg: "请30秒后再试" });
        return;
    }
    let code = this.random(1000, 9999);
    let url = cnst.dk_phoneverifycode_url + "?mobile=" + phone + "&verifyCode=" + code;
    let ret = yield phttp.httpGetAsync(url);
    if (!ret) {
        console.logg("request verify code failed");
        res.send({ code: 500, msg: "request verify code failed" });
        return;
    }
    let obj = JSON.parse(ret);
    if (obj.msg === "操作成功") {
        yield router.redis.setString(phone, code);
        yield router.redis.setString(key, new Date().getTime());
        yield router.redis.setExpire(key, 60 * 60 * 240);//10天过期
        yield router.redis.setExpire(phone, 60 * 60 * 240);//10天过期
        res.send({ code: 200, msg: "succes" });
        return;
    }
    res.send({ code: 500, msg: "request verify code failed" });
});


//http://cy.test.xiangchaopai.com/verify/code?mobile=15158891775&verifyCode=1234
//http://xxxx.com/verify/code?mobile=15158891775&verifyCode=1234
//{"code":"99","msg":"操作成功","data":null}
router.get('/weixin/dk_getPhoneVerifycode', function (req, res) {
    router.dk_getPhoneVerifycode(req, res).catch(function (e) {
        console.logg("dk_getPhoneVerifycode exception ", e.message);
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});


router.dkLogin = P.coroutine(function* (req, res) {
    let phone = req.query.account;
    let password = req.query.password;
    // if (!(/^1(3|4|5|7|8)\d{9}$/.test(phone))) {
    //     console.logg("手机号码格式不对 ", phone);
    //     res.send({ code: 500, msg: '手机号码格式不对' });
    //     return;
    // }
    if (password && password.length < 8) {
        res.send({ code: 500, msg: '请输入8位以上的密码' });
        return;
    }
    if (!password || password.length > 30) {
        res.send({ code: 500, msg: 'invalid password' });
        return;
    }
    let psw = Token.aesEncodeDef(password);
    let ip = ipUtil.getIp(req, res);
    let ret = yield userService.userLoginWithPsw(phone, psw, ip);
    if (ret == null) {
        res.send({ code: 500, msg: '请输入正确的账户和密码' });
        return;
    }
    ret.code = 200;
    ret.password = null;
    console.logg("玩家最近登录的ip", ret.name, ret.account, ip);

    let tokenObj = {
        uid: ret.uid,
        timestamp: new Date().getTime()
    };

    let token = Token.aesEncodeDef(JSON.stringify(tokenObj));
    let cacheKey = redisConst.LOGIN_TOKEN + ":" + ret.uid;
    yield redis.set(cacheKey, token);

    ret.token = Token.aesEncodeDef(ret.uid);
    ret.stoken = Token.aesEncodeDef(ip);
    res.send(ret);
});

router.get('/weixin/dkLogin', function (req, res) {
    router.dkLogin(req, res).catch(function (e) {
        console.logg("dkLogin exception ", e.message);
        if (!res.finished) {
            res.send({ code: 500, msg: "exception" });
        }
    });
});

router.get('/weixin/dkRechargeNotify', function (req, res) {
    router.dkRechargeNotify(req, res).catch(function (e) {
        console.logg("dkRechargeNotify exception ", e.message);
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});


router.get('/weixin/dkRechargeSync', function (req, res) {
    router.dkRechargeNotify(req, res).catch(function (e) {
        console.logg("dkRechargeNotifySync exception ", e.message);
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});


router.dkAddRegUser = P.coroutine(function* (req, res) {
    let mobile = req.query.mobile;
    let nickName = req.query.nickname;
    let password = req.query.password;
    let ss = ["mobile=" + mobile, "nickname=" + nickName, "password=" + password];
    if (!nickName || nickName.length > 20) {
        res.send({ code: 500, msg: 'invalid nickname' });
        return;
    }
    if (password && password.length < 8) {
        res.send({ code: 500, msg: '请输入8位以上的密码' });
        return;
    }
    if (!password || password.length > 30) {
        res.send({ code: 500, msg: 'invalid password' });
        return;
    }
    let psw = Token.aesEncodeDef(password);

    //字符串字典排序
    ss.sort(function (a, b) {
        if (a > b) return 1;
        return -1;
    });
    let s = "";
    for (let i = 0; i < ss.length; i++) {
        let it = ss[i];
        s = s + it + "&";
    }
    let sign = req.query.sign;
    let str = s + cnst.dk_md5key;
    s = Token.md5(str);
    if (s !== sign) {
        console.logg("correct sign=", s, " error sign=" + sign);
        res.send({ code: 500, msg: "invalid sign" });
        return;
    }
    let ip = ipUtil.getIp(req, res);
    let headimgurl = Math.floor(Math.random() * 100) % 83 + 1;
    psw = Token.aesEncodeDef(password);
    console.logg("密码加密 ", psw, password);
    let ret = yield userService.addUserByMobile(mobile, nickName, psw, ip, headimgurl);
    //99表示新增成功，01表示⽤户已经存在，33表示系统异 常
    if (ret.exit === 0) { res.send({ code: "99", msg: "新增用户成功" }); return; }
    if (ret.exit === 1) { res.send({ code: "01", msg: "用户已存在" }); return; }
    res.send({ code: "33", msg: "系统异常" });
});
//mobile ,nickName
//http://localhost:3013/weixin/dkAddRegUser?mobile=13564547975&nickname=hello&password=12345678
//http://localhost:3013/weixin/dkAddRegUser?mobile=13564547976&nickname=hello&password=12345678&sign=65ec305aa49a43521172979b008e45ee
router.get('/weixin/dkAddRegUser', function (req, res) {
    router.dkAddRegUser(req, res).catch(function (e) {
        console.logg("dkAddRegUser exception ", e.message);
        if (!res.finished) { res.send({ code: "33", msg: "exception" }); }
    });
});

router.RandomNum = function (len) {
    let $chars = '0123456789';
    let maxPos = $chars.length;
    let pwd = ''; for (let i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); }
    return pwd;
};

router.getDkArgsSign = function (list, key) {
    let s = "";
    if (!list || list.length === 0) {
        s = cnst.dk_md5key;

        let str = Token.md5(s);
        return str;
    }
    let ss = list;
    ss.sort(function (a, b) {
        if (a > b) return 1;
        return -1;
    });
    for (let i = 0; i < ss.length; i++) {
        s = s + ss[i] + "&";
    }
    if (key) {
        s += key;
    } else {
        s += cnst.dk_md5key;
    }

    return s;
};

router.lockGame = P.coroutine(function* (req, res) {
    let lock = req.query.lock;
    let gameType = req.query.gameType;
    let roomInfo = req.query.roomInfo;
    //1为 锁住 -1 为释放
    let token = req.query.token;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token);
        let uidObj = JSON.parse(uid);
        if (uidObj.uid) {
            uid = uidObj.uid;
        }
    } catch (e) {
        uid = -1;
    }
    if (uid == -1) {
        res.send({ code: 500 });
        return;
    }
    let key = "gaming_" + uid;
    let info = { gameType: gameType, roomInfo: roomInfo };
    let s = JSON.stringify(info);
    console.logg("uid=" + uid, s);
    if (lock === 1) {
        yield router.redis.setString(key, s);
        let hour = 60 * 10;//30分钟冻结时间
        yield router.redis.setExpire(key, hour);
    }
    if (lock === -1) {
        yield router.redis.delString(key);
    }
    res.send({ code: 200 });
});

router.get('/weixin/lockGame', function (req, res) {
    router.lockGame(req, res).catch(function (e) {
        console.logg("lockGame exception ", e.message);
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});


router.getlockGame = P.coroutine(function* (req, res) {
    let token = req.query.token;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token);
    } catch (e) {
        uid = -1;
    }
    if (uid === -1) {
        console.logg("getLockGame uid-1", uid);
        res.send({ code: 500 });
        return;
    }
    let key = "gaming_" + uid;
    ///http://103.230.241.232:3013/weixin/getlockGame?token=b85ab34387a70e9af2a5d7906879adc3&random=1547084357794
    console.logg("getLockGame ", key, uid);
    if (uid == null) {
        res.send({ code: 500 });
        return;
    }
    let gameInfo = yield router.redis.getString(key);
    res.send({ code: 200, gameInfo: gameInfo });
});

router.get('/weixin/getlockGame', function (req, res) {
    router.getlockGame(req, res).catch(function (e) {
        console.logg("getlockGame exception ", e.message);
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });

});